/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bookstore.mvc.controller;

import bookstore.bean.LoginBean;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

/**
 *
 * @author Caleido
 */
public class AccountController extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        try {
            String action = request.getParameter("action");
            String username = request.getParameter("username");
            String email = request.getParameter("email");
            String password = request.getParameter("password");


            if (action.equals("Register")) {
                LoginBean account = LoginBean.register(username, email, password);
                if (account != null) {
                    session.setAttribute("USER", account);
                }
                XMLOutputFactory ouf = XMLOutputFactory.newInstance();
                StringWriter sw = new StringWriter();
                XMLStreamWriter writer = ouf.createXMLStreamWriter(response.getWriter());
                writer.writeStartDocument();
                writer.writeStartElement("Response");
                writer.writeStartElement("Type");
                if (account != null) {
                    writer.writeCharacters("OK");
                } else {
                    writer.writeCharacters("NG");
                }
                writer.writeEndElement();
                writer.writeStartElement("Message");
                if (account != null) {
                    writer.writeCharacters(account.getUsername());
                } else {
                    writer.writeCharacters("Unexpected error occurs. This username may not be available.");
                }
                writer.writeEndElement();
                writer.writeEndElement();
                writer.flush();
                writer.close();
                response.getWriter().flush();
            } else if (action.equals("Login")) {
                LoginBean account = LoginBean.checkLogin(username, password);
                if (account != null) {
                    session.setAttribute("USER", account);
                }
                XMLOutputFactory ouf = XMLOutputFactory.newInstance();
                StringWriter sw = new StringWriter();
                XMLStreamWriter writer = ouf.createXMLStreamWriter(response.getWriter());
                writer.writeStartDocument();
                writer.writeStartElement("Response");
                writer.writeStartElement("Type");
                if (account != null) {
                    writer.writeCharacters("OK");
                } else {
                    writer.writeCharacters("NG");
                }
                writer.writeEndElement();
                writer.writeStartElement("Message");
                if (account != null) {
                    writer.writeCharacters(account.getUsername());
                } else {
                    writer.writeCharacters("Login failed.\nPlease check your username and password.");
                }
                writer.writeEndElement();
                writer.writeEndElement();
                writer.flush();
                writer.close();
                response.getWriter().flush();
            } else if (action.equals("Logout")) {
                session.invalidate();
                XMLOutputFactory ouf = XMLOutputFactory.newInstance();
                StringWriter sw = new StringWriter();
                XMLStreamWriter writer = ouf.createXMLStreamWriter(response.getWriter());
                writer.writeStartDocument();
                writer.writeStartElement("Response");
                writer.writeStartElement("Type");
                writer.writeCharacters("OK");
                writer.writeEndElement();
                writer.writeStartElement("Message");
                writer.writeCharacters("Logout completed.");
                writer.writeEndElement();
                writer.writeEndElement();
                writer.flush();
                writer.close();
                response.getWriter().flush();
            }
        } catch (XMLStreamException ex) {
            Logger.getLogger(AccountController.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
